package com.example.threadPool;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * description: ThreadPools <br>
 * date: 2021/6/10 13:32 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
public class ThreadPools {

    public static final ThreadPoolExecutor demoExcutor = new ThreadPoolExecutor(4,16,5L,
            TimeUnit.MICROSECONDS,new LinkedBlockingDeque<Runnable>(),
            new NameableThreadFactory("demo"));
    private static class NameableThreadFactory implements ThreadFactory{
        private final ThreadGroup group;
        private final AtomicInteger threanNum = new AtomicInteger();
        private final String namePrefix;

        public NameableThreadFactory(String name){
            SecurityManager manager = System.getSecurityManager();
            this.group = manager != null ? manager.getThreadGroup() : Thread.currentThread().getThreadGroup();
            if (name != null && !"".equals(name.trim())) {
                this.namePrefix = "pool-" + name + "-thread-";
            } else {
                this.namePrefix = "pool-default-thread-";
            }
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(this.group, r, this.namePrefix + this.threanNum.getAndIncrement(), 0L);
            if (thread.isDaemon()) {
                thread.setDaemon(false);
            }
            if (thread.getPriority() != Thread.NORM_PRIORITY) {
                thread.setPriority(Thread.NORM_PRIORITY);
            }
            return thread;
        }
    }

}
